package com.bw.user_module.reset;

import android.text.TextUtils;

import androidx.databinding.ObservableField;
import androidx.room.Room;

import com.bw.base_application_sdk.BaseApplication;
import com.bw.common.entity.SaveEntity;
import com.bw.common.field.EventBusEntity;
import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.common.utils.ToastShowUtils;
import com.bw.network_sdk.BaseEntity;
import com.bw.user_module.dao.UserDatabase;
import com.bw.user_module.login.LoginViewModel;
import com.bw.user_module.user.UserEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ResetViewModel extends BaseViewModel<ResetRespository> {

    public ObservableField<String>pwd=new ObservableField<>();
    public ObservableField<String>confirmpwd=new ObservableField<>();
    public String phone="111";//用户手机号

    public void confirm(){
        if (TextUtils.isEmpty(phone)){
            ToastShowUtils.showShort("手机号错误");
            return;
        }
        if (TextUtils.isEmpty(pwd.get())){
            ToastShowUtils.showShort("密码不能为空");
            return;
        }
        if (TextUtils.isEmpty(confirmpwd.get())){
            ToastShowUtils.showShort("确认密码不能为空");
            return;
        }
        if (pwd.get().equals(confirmpwd.get())){
            ToastShowUtils.showShort("密码不同");
            return;
        }
        Map<String,Object>map = new HashMap<>();
        map.put("mobile",phone);
        map.put("pwd",pwd.get());
        respository.requestReset(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    public void onResult(BaseEntity entity) {
        if (entity instanceof UserEntity){
            UserEntity userEntity = (UserEntity) entity;
            UserDatabase db = Room.databaseBuilder(BaseApplication.getInstance(),
                    UserDatabase.class, "user.db").build();
            respository.saveUser(userEntity,db)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(ResetViewModel.this);
        }else if (entity instanceof SaveEntity){
            EventBusEntity eventBusEntity1 = new EventBusEntity();
            eventBusEntity1.action = "refresh";
            EventBus.getDefault().post(eventBusEntity1);
            finishPage();
            EventBusEntity eventBusEntity = new EventBusEntity();
            eventBusEntity.action = "finish";
            EventBus.getDefault().post(eventBusEntity);
        }
    }

    @Override
    protected void initData() {

    }
}
